﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FluentData;
using Framework.Properties;

namespace Framework.Data
{
    /// <summary>
    /// 数据库连接辅助类；用于分库连接，找到酒店分库连接字符串并创建连接对象。
    /// </summary>
    internal static class ConnectionHelper
    {
        private static List<HiveMap> _hiveMaps;

        internal static List<HiveMap> HiveMapCollection
        {
            get
            {
                if (_hiveMaps == null)
                {
                    var sql = "SELECT sOrgID, sSafeConnString, sType FROM HiveMap";

                    using (var dbBase = DataHelper.GetBaseDbContext())
                    {
                        _hiveMaps = dbBase.Sql(sql).QueryMany<HiveMap>(delegate(HiveMap hiveMap, IDataReader row)
                        {
                            hiveMap.OrgId = row.GetString("sOrgID");
                            hiveMap.ConnectionString = ConnectionStringCipher.DecryptCipher(row.GetString("sSafeConnString"));

                            string dbType = row.GetString("sType").ToLower();
                            if (dbType == "basesqlconn")
                                hiveMap.DatabaseType = DatabaseType.Base;
                            else if (dbType == "bizsqlconn")
                                hiveMap.DatabaseType = DatabaseType.Hotel;
                            else
                                throw new FrameworkException(ExceptionCode.FRAMEWORK_DEFAULT_EXCEPTIONCODE, "Resources.DatabaseNotFound");
                        });
                    }
                }

                return _hiveMaps;
            }
        }

        internal static IDbContext GetHotelDbContext(string hotelId, DatabaseType dbType)
        {
            var hiveMap = HiveMapCollection.Find(s => s.OrgId == hotelId && s.DatabaseType == dbType);

            if (hiveMap != null)
            {
                IDbContext dbContext = new DbContext().ConnectionString(hiveMap.ConnectionString,
                                                                        new SqlServerProvider());
                return dbContext;
            }

            return null;
        }
    }
    
    public enum DatabaseType{
         /// </summary>
        Base,
        /// <summary>
        /// 一群酒店的组合库。如某品牌底下所有酒店的库
        /// </summary>
        Group,
        /// <summary>
        /// 单个酒店的库
        /// </summary>
        Hotel
    }
    
}
